package com.cfzx.http


import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.BuildConfig
import com.huanglejing.shanggou.common.AppContext
import com.huanglejing.shanggou.http.DADIGsonConverter
import com.huanglejing.shanggou.http.DADIService
import com.huanglejing.shanggou.http.LoggerInterceptor
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.utils.C.APIV1.REGISTER
import com.huanglejing.shanggou.utils.C.APIV1.VALILD_YZM
import com.huanglejing.shanggou.utils.NetworkUtil
import com.huanglejing.shanggou.utils.ToastUtils
import okhttp3.Cache
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit


/**
 * Created by Administrator on 2016/7/22 0022.
 */
object NetClient {

    private const val TAG = "NetClient"
    //    private static final Converter.Factory gsonConverterFactory = GsonConverterFactory.createPresenter();
    private val rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create()
    private val CFZX_Interceptor by lazy {
        Interceptor { chain ->
            //方案二：无网读缓存，有网根据过期时间重新请求
            //http://www.jianshu.com/p/2710ed1e6b48
            val netWorkConection = NetworkUtil.isNetAvailable(AppContext.get())
            var request = chain.request()
            if (!netWorkConection) {
                KLog.i(TAG, "NO NetWork , FORCE_CACHE")
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build()
            } else {
                KLog.i(TAG, "Has NetWork , go on")
                var contentType="application/json;charset=UTF-8"
             //   ToastUtils.toastLong("请求地址是 ${request?.url()?.toString()}")
                if (request?.url()?.toString()?.contains(VALILD_YZM)?:false
                || request?.url()?.toString()?.contains(REGISTER)?:false) {
                    contentType="application/x-www-form-urlencoded;charset=UTF-8"
                }else{
                    contentType="application/json;charset=UTF-8"
                }
                request = request.newBuilder()
                        .headers(request.headers())
                        .header("Content-Type", contentType)
                        .build()

                KLog.i(TAG, "${request.url()} header ${request?.headers()?.toString()}")
                KLog.e(TAG, " body111    ${request?.body()?.contentType()}")
            }
            //添加token
            val response = chain.proceed(request)
            if (netWorkConection) {
                //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                //@Headers("Cache-Control: max-age=640000")
                val cacheControl = request.cacheControl().toString()
                response.newBuilder().removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                        .header("Cache-Control", cacheControl)
                        .build()
            } else {
                val maxStale = 60 * 60 * 24 * 7 //一周
                response.newBuilder().removeHeader("Pragma").header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).build()
            }
            response
        }
    }
    //baseurl=http://old.dadisoft.cn/
    val oldDaDiService by lazy {
        createService<DADIService>(C.APIV1.BASE_URL_OLD)
    }
    //baseurl=http://dadisoft.cn
    val daDiService by lazy {
        createService<DADIService>(C.APIV1.BASE_URL_NEW)
    }

    inline fun <reified T> createService(baseUrl: String): T = getRetrofit(baseUrl).create(T::class.java)

    fun getRetrofit(baseUrl: String) = Retrofit.Builder().client(okHttpClient).baseUrl(baseUrl)
            .addConverterFactory(DADIGsonConverter())//
            //  .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(rxJavaCallAdapterFactory)
            .build()

    //endregion

    val okHttpClient by lazy {
        //设置缓存路径
        val httpCacheDirectory = File(AppContext.get().cacheDir, "OK_HTTP_CACHE")
        //设置缓存 100M
        val cache = Cache(httpCacheDirectory, 100 * 1024 * 1024.toLong())

        val client = OkHttpClient.Builder()
                .writeTimeout((60 * 1000).toLong(), TimeUnit.MILLISECONDS)
                .readTimeout((60 * 1000).toLong(), TimeUnit.MILLISECONDS)
                .connectTimeout((60 * 1000).toLong(), TimeUnit.MILLISECONDS)
                .cache(cache)
                .addNetworkInterceptor(CFZX_Interceptor)
        if (BuildConfig.DEBUG) {
            client.addInterceptor(LoggerInterceptor("OK_HTTP"))
        }
        client.build()
    }

}
